package service.imp;

import Dao.imp.UserDao;
import com.alibaba.fastjson.JSON;
import entity.Msg;
import entity.User;
import mapper.UserMapper;
import service.IUserService;

import java.util.Date;

/**
 * @author Jiuyuesheng
 * @date 2019/12/29  10:27
 */
public class UserService implements IUserService {
    private UserMapper userDao = new UserDao();

    /**
     * 1.根据username查询uid
     * 2.根据uid得到User
     * 3.从User中判断密码是否正确
     * 4.密码正确则返回正确uid,否则返回-1
     */
    @Override
    public int doLogin(User user) {
        int uid = userDao.queryUserUid(user.getUsername());
        if (uid > 0) {
            User userResult = userDao.queryUser(uid);
            if (userResult.getPassword().equals(user.getPassword())) {
                return uid;
            }
        }

        return -1;
    }

    @Override
    public String doRegister(User user) {
        /**
         * 1.判断数据库中username是否相同
         *    --注册成功 返回200
         *    --注册失败 返回404
         */

        String responseString = "";
        user.setModifytime(new Date());
        int uid = userDao.queryUserUid(user.getUsername());
        Msg msg = new Msg();
        msg.setStatus(404);
        msg.setData("注册失败");
        if (uid == -1) {
            int rs = userDao.addUser(user);
            if (rs > 0) {
                msg.setStatus(200);
                msg.setData("注册成功");
            }
        }

        responseString = JSON.toJSONString(msg);
        return responseString;
    }
}
